package com.zeta.demo.mq.controller;

import cn.hutool.core.bean.BeanUtil;
import com.zeta.api.model.DemoDTO;
import com.zeta.demo.mq.model.entity.DemoMq;
import com.zeta.demo.mq.model.param.DemoMqSaveDTO;
import com.zeta.demo.mq.model.param.DemoMqUpdateDTO;
import com.zeta.demo.mq.service.IDemoMqService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zetaframework.annotation.log.SysLog;
import org.zetaframework.annotation.satoken.PreAuth;
import org.zetaframework.base.result.ApiResult;
import org.zetaframework.controller.SuperSimpleController;
import org.zetaframework.controller.curd.SaveController;
import org.zetaframework.controller.curd.UpdateController;
import org.zetaframework.mq.MessageSender;
import org.zetaframework.mq.constants.DemoMqConstants;

/**
 * Mq测试
 *
 * @author gcc
 */
@Slf4j
@PreAuth(enabled = false)
@Tag(name = "Mq测试", description = "Mq测试")
@RestController
@RequestMapping("/demo/mq")
@RequiredArgsConstructor
public class DemoMqController extends SuperSimpleController<IDemoMqService, DemoMq>
    implements SaveController<DemoMq, DemoMqSaveDTO>,
        UpdateController<DemoMq, DemoMqUpdateDTO>
{

    private final MessageSender messageSender;

    /**
     * 新增
     *
     * @param saveDTO SaveDTO 保存对象
     * @return ApiResult<Boolean>
     */
    @SysLog
    @Override
    public ApiResult<Boolean> save(DemoMqSaveDTO saveDTO) {
        // SaveDTO -> Entity
        DemoMq entity = BeanUtil.toBean(saveDTO, DemoMq.class);
        if (!service.save(entity)) {
            return fail("操作失败", false);
        }

        // 异步发送MQ消息 给指定消费者
        DemoDTO message = BeanUtil.toBean(entity, DemoDTO.class);
        messageSender.to(DemoMqConstants.DEMO_BINDING_NAME)
                .routingKey(DemoMqConstants.DEMO_ROUTING_KEY_CREATE)
                .sendMessageAsync(message);
        return success(true);
    }

    /**
     * 修改
     *
     * @param updateDTO UpdateDTO 修改对象
     * @return ApiResult<Boolean>
     */
    @SysLog
    @Override
    public ApiResult<Boolean> update(DemoMqUpdateDTO updateDTO) {
        // UpdateDTO -> Entity
        DemoMq entity = BeanUtil.toBean(updateDTO, DemoMq.class);
        if (!service.updateById(entity)) {
            return fail("操作失败", false);
        }

        // 异步发送MQ消息 给指定消费者
        DemoDTO message = BeanUtil.toBean(entity, DemoDTO.class);
        messageSender.to(DemoMqConstants.DEMO_BINDING_NAME)
                .routingKey(DemoMqConstants.DEMO_ROUTING_KEY_UPDATE)
                .sendMessageAsync(message);
        return success(true);
    }

}
